﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using WPF_MVVM_PathSearchUtil.data_access;
using WPF_MVVM_PathSearchUtil.Models;
using WPF_MVVM_PathSearchUtil.service;
using WPF_MVVM_PathSearchUtil.util;
using WPF_MVVM_PathSearchUtil.ViewModels.commom;
using WPF_MVVM_PathSearchUtil.ViewModels.common;
using WPF_MVVM_PathSearchUtil.Views;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MessageBox = System.Windows.MessageBox;

namespace WPF_MVVM_PathSearchUtil.ViewModels
{
    public class MainWindowViewModel : Bindable
    {
        #region props
        private MainWindowService mainService;
        private CSVReadOrWrite access;
        private int[] isDESC = { 0, 0, 0, 0, 0 };
        private int indexNow;
        private string findWord;
        private string searchPath;
        public string SearchPath
        {
            get { return searchPath; }
            set { SetProperty(ref searchPath, value); }
        }
        private bool isChecked = false;
        public bool IsChecked
        {
            get { return isChecked; }
            set { SetProperty(ref isChecked, value); }
        }
        private int selectedIndex = -1;
        public int SelectedIndex
        {
            get { return selectedIndex; }
            set { SetProperty(ref selectedIndex, value); }
        }
        private ObservableCollection<int> findResult;
        private ObservableCollection<FileInfoModel> fileList;
        public ObservableCollection<FileInfoModel> FileList
        {
            get { return fileList; }
            set { SetProperty(ref fileList, value); }
        }
        public Window CurrentWindow { get; set; }
        #endregion

        #region command
        public BaseCommand WithdrawButton { get; set; }
        public BaseCommand SelectPathButton { get; set; }
        public BaseCommand DoneButton { get; set; }
        public BaseCommand FindButton { get; set; }
        public BaseCommand NextButton { get; set; }
        public BaseCommand ExCSVButton { get; set; }
        public BaseCommand ImCSVButton { get; set; }

        public BaseCommand<DataGridSortingEventArgs> SortingEvent { get; set; }
        public BaseCommand<KeyEventArgs> KeyDownEvent { get; set; }
        public BaseCommand SelectChangedEvent { get; set; }
        #endregion

        #region init
        public MainWindowViewModel(Window window)
        {
            CurrentWindow = window;
            //access = new ServerSQLite();
            access = new LocalSQLite();
            fileList = new ObservableCollection<FileInfoModel>();
            findResult = new ObservableCollection<int>();
            WithdrawButton = new BaseCommand();
            SelectPathButton = new BaseCommand();
            FindButton = new BaseCommand();
            NextButton = new BaseCommand();
            ExCSVButton = new BaseCommand();
            ImCSVButton = new BaseCommand();
            DoneButton = new BaseCommand();
            SelectChangedEvent = new BaseCommand();
            SortingEvent = new BaseCommand<DataGridSortingEventArgs>();
            KeyDownEvent = new BaseCommand<KeyEventArgs>();
            mainService = new MainWindowServiceImpl();
            WithdrawButton.SubScribe(x => { Withdraw(); });
            SelectPathButton.SubScribe(x => { SelectPath(); });
            FindButton.SubScribe(x => { OpenFindForm(); });
            NextButton.SubScribe(x => { SearchNext(); });
            ExCSVButton.SubScribe(x => { ExCSV(); });
            ImCSVButton.SubScribe(x => { ImCSV(); });
            SortingEvent.SubScribe(Sorting) ;
            KeyDownEvent.SubScribe(KeyDown);
            SelectChangedEvent.SubScribe(x => { SelectChanged(); });
        }
        #endregion

        #region method
        /// <summary>
        /// 抽出
        /// </summary>
        public void Withdraw()
        {
            findResult.Clear();
            Resp resp = mainService.WithdrawPath(ref fileList, searchPath, isChecked);
            if (resp.Code == 0)
            {
                MessageBox.Show("抽出成功", "提示");
            }
            else
            {
                MessageBox.Show(resp.Message, "提示");
            }
        }

        /// <summary>
        /// 打开检索窗口
        /// </summary>
        public void OpenFindForm()
        {
            if (fileList.Count <= 0)
            {
                MessageBox.Show("没有可检索的列表。","提示");
                return;
            }
            //注册消息接收者，回调Find
            Messenger.Default.Register<MyMessage>(this, Find);
            FindForm findForm = new FindForm();
            findForm.Owner = CurrentWindow;
            findForm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            findForm.ShowDialog();
        }

        /// <summary>
        /// 选择路径
        /// </summary>
        public void SelectPath()
        {
            FolderBrowserDialog folderDlg = new FolderBrowserDialog();
            if (folderDlg.ShowDialog() == DialogResult.OK)
            {
                SearchPath = folderDlg.SelectedPath;
            }
        }

        /// <summary>
        /// 获取消息 检索
        /// </summary>
        /// <param name="message"></param>
        public void Find(MyMessage message)
        {
            findWord = message.Messages;
            Resp resp = mainService.Find(ref findResult,fileList,findWord);
            UnregisterMessage();
            if (resp.Code != 0)
            {
                MessageBox.Show(resp.Message, "提示");
            }
            else
            {
                indexNow = findResult[0];
                SetSelectedIndex(findResult[0]);
            }
        }

        /// <summary>
        /// 清除datagrid选中效果，并选中指定行
        /// </summary>
        /// <param name="index"></param>
        public void SetSelectedIndex(int index)
        {
            SelectedIndex = -1;
            SelectedIndex = index;
        }

        /// <summary>
        /// 检索下一个
        /// </summary>
        public void SearchNext()
        {
            Resp resp = mainService.SearchNext(ref findResult,fileList,findWord,indexNow);
            if (resp.Code != 0)
            {
                MessageBox.Show(resp.Message, "提示");
            }
            else
            {
                indexNow = Convert.ToInt32(resp.Date);
                SetSelectedIndex(indexNow);
            }
        }

        /// <summary>
        /// 导出CSV
        /// </summary>
        public void ExCSV()
        {
            Resp resp = mainService.WriteByServerOrLocal(access,fileList);
            if (resp.Code == -2)
            {
                return;
            }
            if (resp.Code != 0)
            {
                MessageBox.Show(resp.Message);
            }
            if (resp.Code == 0)
            {
                MessageBox.Show(resp.Date.ToString(), "提示");
            }
        }

        /// <summary>
        /// 读取CSV
        /// </summary>
        public void ImCSV()
        {
            Resp resp = mainService.ReadByServerOrLocal(access,ref fileList);
            if (resp.Code == -2) {
                return;
            }
            if (resp.Code != 0)
            {
                MessageBox.Show(resp.Message);
            }
            if (resp.Code == 0)
            {
                MessageBox.Show("读取成功。", "提示");
            }
        }

        /// <summary>
        /// 注销消息接收者
        /// </summary>
        public void UnregisterMessage()
        {
            // 取消注册接收者
            Messenger.Default.Unregister<MyMessage>(this);
        }
        
        /// <summary>
        /// 点击标题排序
        /// </summary>
        public void Sorting(DataGridSortingEventArgs e)
        {
            Resp resp = mainService.ToSort(ref fileList, ref isDESC, e);
            
        }

        /// <summary>
        /// keyDown
        /// </summary>
        /// <param name="e"></param>
        public void KeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.Escape) Close();
            if (e.Key == Key.F1) ImCSV();
            if (e.Key == Key.F3) SearchNext();
            if (e.Key == Key.F7) OpenFindForm();
            if (e.Key == Key.F8) Withdraw();
            if (e.SystemKey == Key.F10) ExCSV();
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        public void Close()
        {
            UnregisterMessage();
            CurrentWindow.Close();
        }

        /// <summary>
        /// 选中行变化，发送给view，保持选中行在画面内
        /// </summary>
        public void SelectChanged()
        {
            if(SelectedIndex >=0 && SelectedIndex < fileList.Count)
            {
                var message = new MyMessage
                {
                    SelectedIndex = SelectedIndex
                };
                Messenger.Default.Send(message);
            }
        }
        #endregion
    }
}
